# -*- coding: utf-8 -*-
# @Time        :2025/4/7 17:28
# @Author      :文刀水寿
# @File        : views.py
"""
 @Description :路由 +  视图函数
"""
# 蓝图
from flask import Blueprint, render_template, request, redirect

# 可以管理多个蓝图
blue = Blueprint('user', __name__)


# blue2 = Blueprint('user2', __name__)

# 首页
@blue.route('/home')
@blue.route('/')
def home():
    # 获取cookie
    username = request.cookies.get('user')

    return render_template('home.html', username=username)

# 登录
@blue.route('/login', methods=['GET', 'POST'])
def login():
    # GET访问页面
    if request.method == 'GET':
        return render_template('login.html')
    # post 请求实现登录功能
    elif request.method == 'POST':
        pass
        # 1. 获取前端返回的数据
        username = request.form.get('username')
        passworld = request.form.get('passworld')

        # 2. 模拟登录 : 用户名和密码验证
        if username == 'lisi' and passworld == '123':
            # 登录成功
            response = redirect('/home')

            # 3. 设置Cookie: 不能有中文
            response.set_cookie('user', username) # 默认浏览器关闭则cookie失效
            # 过期时间：
                # max_age: 秒
                # response.set_cookie('user', username, max_age=3600 * 24 * 7)
                # expires: 指定datatime日期
                # response.set_cookie('user', username, expires=datetime.datetime(2023,12,12))
            return response

        else:
            return "用户或密码错误123"

# 注销
@blue.route('/logout')
def logout():
    # 删除cookie
    response = redirect('/home')
    response.delete_cookie('user')
    return response